package weeny.pre.util;

import java.util.Collection;
import java.util.List;

import prefuse.data.parser.CollectionParser;
import prefuse.data.parser.DataParseException;
import prefuse.data.parser.DataParser;

/**
 * Implements the DataParser interface, so we can use it in Prefuse Table.
 *
 * @author weeny
 */
public class Counter<T> extends weeny.util.Counter<T> implements DataParser{
	public Counter(){
		super();
	}
	public Counter(boolean supportNegative) {
		super(supportNegative);
	}
	public Counter(Collection coll){
		super(coll);
	}
	//-------------------------------------------------------------------------
	//DataParser functions
	public boolean canParse(String text) {
		try {
			parse(text);
			return true;
		} catch (Exception e) { }
		return false;
	}
	public boolean compatible(Class type) {
		return getType() == type;
	}
	public String format(Object value) {
		return ((Counter)value).encode();
	}
	public Class getType() {
		return Counter.class;
	}
	public Object parse(String text) throws DataParseException {
		try {
			List<String> array = CollectionParser.csv2List(text);
			Counter result = new Counter(Boolean.parseBoolean(array.get(0)));
			for(int i = 1; i<array.size(); i+=2){
				Number val = null;
				try {
					val = Integer.parseInt(array.get(i+1));
				} catch (NumberFormatException e) {
					val = Double.parseDouble(array.get(i+1));
				}
				result.increase(array.get(i), val);
			}
			return result;
		} catch (Exception e) {
			throw new DataParseException(e);
		}
	}
}
